﻿/*********************************************************************
 * Copyright 2012 Fan Deng.
 * 
 * This file is part of uscis-status-tracker.
 * 
 * uscis-status-tracker is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * uscis-status-tracker is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;

namespace USCISStatusTracker
{
	class ReceiptPool
	{
		private BindingList<USCISStatus> pool;
		public int GetCount()
		{
			return pool.Count;
		}
		public void Remove(USCISStatus item)
		{
			pool.Remove(item);
		}
		public void Remove(int id)
		{
			try
			{
				pool.RemoveAt(id);
			}
			catch
			{
				throw new ApplicationException("Uncaught exception");
			}
		}
		private int Contains(USCISStatus item)
		{
			for (int i = 0; i < pool.Count; i++)
			{
				if (item.ReceiptNumber == pool[i].ReceiptNumber)
				{
					return i;
				}
			}
			return -1;
		}
		public void Add(USCISStatus item)
		{
			int pos = this.Contains(item);
			if (pos > -1)
			{
				pool[pos] = item;
			}
			else
			{
				pool.Add(item);
			}
		}
		public void AddDummy()
		{
			USCISStatus status = USCISStatus.Track("SRC1290238566");
			//USCISStatus status = new USCISStatus("SRC1290238563", "nothing", "no nothing");
			this.Add(status);
		}
		public BindingList<USCISStatus> GetData()
		{
			return pool;
		}
		public void RefreshAll()
		{
			for (int i = 0; i < pool.Count; i++)
			{
				pool[i] = pool[i].Refresh();
			}
		}
		public static ReceiptPool FromFile(string fileName)
		{
			ReceiptPool receiptPool = new ReceiptPool();
			try
			{
				using (Stream stream = File.Open(fileName, FileMode.Open))
				{
					BinaryFormatter bin = new BinaryFormatter();
					receiptPool.pool = (BindingList<USCISStatus>)bin.Deserialize(stream);
				}
			}
			catch (IOException)
			{
				receiptPool.pool = new BindingList<USCISStatus>();
			}
			return receiptPool;
		}
		public bool ToFile(string fileName)
		{
			try
			{
				using (Stream stream = File.Open(fileName, FileMode.Create))
				{
					BinaryFormatter bin = new BinaryFormatter();
					bin.Serialize(stream, pool);
				}
			}
			catch (IOException)
			{
				return false;
			}
			return true;
		}
	}
}
